package pers.cj.pdos.controller;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.constant.OrderType;
import pers.cj.pdos.controller.base.BaseController;

import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.ExcelCustom;
import pers.cj.pdos.excel.ExcelCustomListener;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.CustomVo;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 数据库表格操作
 */
@Controller
@RequestMapping("/custom")
public class CustomExcelController extends BaseController {
    @Autowired
    ICustomTypeService customTypeService;
    @Autowired
    ICustomService customService;
    @Autowired
    IUserService userService;
    @Autowired
    IOrderRuleService orderRuleService;

    @RequiresPermissions("custom:import")
    @RequestMapping("/customImport")
    public String customImport() {
        return "custom/customImport";
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("custom:export")
    @RequestMapping("/custom/export")
    public ResponseData export(String search,
                               String status,
                               String customTypeId,
                               String no,
                               String name,
                               String unitTel,
                               String phone,
                               String contacts,
                               String remark,
                               String userId) {
        Company company = getCompany();

        UserVo userVo = getLoginUserVo();
        List<CustomVo> customVoList = customService.listVoPage(company.getId(),
                null,
                null,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                customTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getViewCustomStoreId(userVo,null),
                userId);


        String fileName = "客户列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelCustom.class);
            sheet1.setSheetName("客户信息");
            writer.write(genExcelCustomList(customVoList), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("客户列表导出失败");
        }
    }

    private List<ExcelCustom> genExcelCustomList(List<CustomVo> customVoList) {
        List<ExcelCustom> list = new ArrayList<>();
        for (CustomVo customVo : customVoList){
            ExcelCustom excel = new ExcelCustom();
            excel.setType(customVo.getCustomType().getName());
            excel.setNo(customVo.getNo());
            excel.setName(customVo.getName());
            excel.setUser(customVo.getUser() == null ? "" : customVo.getUser().getName());
            excel.setUnitTel(customVo.getUnitTel());
            excel.setContacts(customVo.getContacts());
            excel.setPhone(customVo.getPhone());
            excel.setTax(customVo.getTax());
            excel.setEmail(customVo.getEmail());
            excel.setCode(customVo.getCode());
            excel.setWechat(customVo.getWechat());
            excel.setQq(customVo.getQq());
            excel.setAddress(customVo.getAddress());
            excel.setStatus(customVo.getStatus()==1 ? "启用" : "停用");
            excel.setRemark(customVo.getRemark());
            list.add(excel);
        }
        return list;
    }

    @ResponseBody
    @RequiresPermissions("custom:import")
    @RequestMapping(value = "/custom/importCustom", method = RequestMethod.POST)
    public ResponseData importCustom(MultipartFile excelFile) {
        Company company = getCompany();
        try {
            if(excelFile == null){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            //文件名
            String uploadName= excelFile.getOriginalFilename();
            if (Utils.isEmpty(uploadName)) {
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }
            String type = uploadName.substring(uploadName.lastIndexOf(".")+1);
            if (!"xlsx".equals(type)){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            InputStream inputStream = excelFile.getInputStream();
            ExcelCustomListener listener = new ExcelCustomListener();
            listener.init(company, getLoginUserVo());

            TimeLog.getInstance().begin(getClass(),"读取");

            ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
            excelReader.read(new Sheet(1,1, ExcelCustom.class));
            TimeLog.getInstance().end();

            TimeLog.getInstance().begin(getClass(),"保存数据");
            if (!Utils.isEmpty(listener.getCustomList())) {
                customService.insert(listener.getCustomList(), listener.getCustomTypeList());
            }
            TimeLog.getInstance().end();

            if (Utils.isEmpty(listener.getDataMsgList())){
                return ResponseData.success(null);
            } else {
                ResponseData responseData = new ResponseData();
                responseData.setCode(3);
                responseData.setMsg("部分客户未导入成功");
                responseData.setData(listener.getDataMsgList());
                return responseData;
            }
        }  catch (Exception e) {
            return ResponseData.fail("客户导入失败");
        }

    }
}
